package com.ganzi.ganziserver.service.imp;

import com.ganzi.ganziserver.core.SystemLog;
import com.ganzi.ganziserver.core.User;
import com.ganzi.ganziserver.core.UserLog;
import com.ganzi.ganziserver.core.UserRoles;
import com.ganzi.ganziserver.dao.UserDao;
import com.ganzi.ganziserver.dao.UserLogDao;
import com.ganzi.ganziserver.dao.UserRolesDao;
import com.ganzi.ganziserver.service.UserService;
import com.ganzi.ganziserver.shiro.redis.OtherCache.UserCache;
import com.ganzi.ganziserver.shiro.redis.RedisCacheManager;
import com.ganzi.ganziserver.utils.GetTime;
import com.ganzi.ganziserver.utils.OtherException;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.crypto.SecureRandomNumberGenerator;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class UserServiceImp implements UserService{

    private static Logger log = LoggerFactory.getLogger(SendServiceImp.class);

    @Autowired
    UserDao userDao;
    @Autowired
    UserLogDao logDao;
    @Autowired
    UserCache cache;
    @Autowired
    UserRolesDao userRolesDao;
    @Autowired
    RedisCacheManager cacheManager;
    
    @Override
    public User findUserByName(String name) throws Exception {
        User u = null;
        if(StringUtils.isNotBlank(name)){
            u = userDao.findUserByName(name);
        }
        return u;
    }

    @Override
    public User findUserByid(long id) throws Exception {
        return null;
    }


    @Override
    @Transactional(propagation = Propagation.REQUIRED,isolation = Isolation.DEFAULT,timeout=36000,rollbackFor=Exception.class)
    public void regist(String name, String pass,long roleId) throws Exception {
        User user = userDao.findUserByName(name);
        if(user != null)throw new OtherException("账号已经存在");
        SecureRandomNumberGenerator secureRandomNumberGenerator=new SecureRandomNumberGenerator();
        String salt= secureRandomNumberGenerator.nextBytes().toHex();
        String pa= new Md5Hash(pass+":"+name+salt).toBase64();
        String passmd5= new Md5Hash(pa).toBase64();
        User u = User.builder().userName(name).passWord(passmd5).locked(0).salt(salt).roleId("0").build();
        userDao.insertUser(u);
        UserRoles userRole = UserRoles.builder().roleId(roleId).userId(u.getId()).build();
        userRolesDao.insertUserRoles(userRole);
    }

    @Override
    public void loginLog(User user){
        try{
            if(user != null){
                UserLog userLog = UserLog.builder().userId(user.getId()).information("登录成功").createTime(GetTime.getNowTime()).build();
                logDao.insertUserLog(userLog);
            }else{
                log.info("存储登录日志失败,用户对象为null");
            }
        }catch (Exception e){
            log.info("存储登录日志出错："+e.getMessage());
        }
    }

    @Override
    public void changePassWord(String password) throws Exception {
        User tempUser = cache.getUserByPrincipal();
        if(tempUser == null){
            throw new OtherException("未登录");
        }else{
            String name = tempUser.getUserName();
            String salt = tempUser.getSalt();
            String pa= new Md5Hash(password+":"+name+salt).toBase64();
            String passmd5= new Md5Hash(pa).toBase64();
            tempUser.setPassWord(passmd5);
            userDao.updateUser(tempUser);
        }
    }

    @Override
    public void updateRandom(User user) throws Exception {
        if(user != null){
            userDao.updateUser(user);
        }
    }

    @Override
    public List<User> findAllUser() throws Exception {
        return userDao.findAllUser();
    }


    @Override
    public void lockUser(long id,int lock) throws Exception {
        userDao.lockUser(id,lock);
    }
    @Override
    public void changeRole(long id,long role) throws Exception {
        List<UserRoles> m = userRolesDao.findUserRolesByUserId(id);
        UserRoles userRoles;
        if(m != null && m.size()>0){
            userRoles = m.get(0);
            userRoles.setRoleId(role);
        }else{
            userRoles = UserRoles.builder().userId(id).roleId(role).build();
        }
        userRolesDao.update(userRoles);
        //清除权限缓存
        User user = userDao.findUserById(id);
        if(user != null)
        cacheManager.getCache("authorizationCache").remove(user.getUserName());
    }

//    public static void main(String[] args) {
//        SecureRandomNumberGenerator secureRandomNumberGenerator=new SecureRandomNumberGenerator();
//        String salt= secureRandomNumberGenerator.nextBytes().toHex();
//        String pa= new Md5Hash("oooooo"+":"+"admin"+salt).toBase64();
//        String passmd5= new Md5Hash(pa).toBase64();
//        System.out.println("密码"+passmd5);
//        System.out.println("--"+salt);
//    }
}
